import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<SelectCommunityViewState> buildReducer() {
  return asReducer(
    <Object, Reducer<SelectCommunityViewState>>{
      SelectCommunityViewAction.action: _onAction,
      SelectCommunityViewAction.onGetData: _onGetData,
      SelectCommunityViewAction.onTextChange: _onTextChange,
    },
  );
}

SelectCommunityViewState _onAction(
    SelectCommunityViewState state, Action action) {
  final SelectCommunityViewState newState = state.clone();
  return newState;
}

SelectCommunityViewState _onTextChange(
    SelectCommunityViewState state, Action action) {
  final SelectCommunityViewState newState = state.clone()
    ..showClose = action.payload.toString().length != 0;
  return newState;
}

SelectCommunityViewState _onGetData(
    SelectCommunityViewState state, Action action) {
  int page = action.payload['page'];
  List items = action.payload['items'];
  final SelectCommunityViewState newState = state.clone();
  if (items == null) {
    newState.currentPage = page;
    newState.refreshController.finishLoad(noMore: true);
    newState.refreshController.finishRefresh();
    newState.items = items;
  } else {
    if (page == 1) {
      newState.items = items;
      newState.refreshController.finishRefresh();
    } else {
      List tmp = [];
      tmp.addAll(newState.items);
      tmp.addAll(items);
      newState.items = tmp;
    }
    newState.currentPage = page;
    newState.refreshController.finishLoad(noMore: items.length == 0);
  }

  return newState;
}
